<template>
  <LayoutNav></LayoutNav>
  <div class="container">
    <div class="wholesaler-detail">
      <!-- 批发商信息卡片 -->
      <el-card class="info-card">
        <div class="wholesaler-info">
          <div class="left">
            <el-avatar 
              :size="100" 
              :src="wholesalerInfo.avatar"
            />
          </div>
          <div class="right">
            <h2 class="name">{{ wholesalerInfo.wholesalerName }}</h2>
            <div class="info-item">
              <el-icon><Location /></el-icon>
              <span>{{ wholesalerInfo.location }}</span>
            </div>
            <div class="info-item">
              <el-icon><Phone /></el-icon>
              <span>{{ wholesalerInfo.phone }}</span>
            </div>
            <div class="info-item">
              <el-icon><Message /></el-icon>
              <span>{{ wholesalerInfo.description }}</span>
            </div>
            <div class="actions">
              <el-button type="primary" @click="handleContact">
                <el-icon><ChatDotRound /></el-icon>
                联系批发商
              </el-button>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 商品列表区域 -->
      <div class="goods-section">
        <div class="section-header">
          <h3>全部商品</h3>
          <div class="filters">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索商品"
              prefix-icon="Search"
              clearable
              @keyup.enter="handleSearch"
            />
            <el-button type="primary"  @click="handleSearch">搜索商品</el-button>
          </div>
        </div>

        <!-- 商品列表 -->
        <el-row :gutter="20">
          <el-col 
            :lg="6" 
            v-for="item in pageList" 
            :key="item.good_id"
          >
            <el-card 
              class="goods-card" 
              shadow="hover"
              @click="goToGoodsDetail(item.good_id)"
            >
              <el-image 
                :src="item.images" 
                fit="cover"
                class="goods-image"
              />
              <div class="goods-info">
                <h4 class="goods-name">{{ item.good_name }}</h4>
                <p class="goods-desc">{{ item.description }}</p>
                <div class="goods-price">
                  <span class="price">¥{{ item.price }}</span>
                  <span class="min-order">起订量：{{ item.minOrder }}件</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[12]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
  <LayoutFooter/>
</template>

<script setup>
import { ref, computed, onMounted, watch} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Location, Phone, Message, ChatDotRound, Star, Search } from '@element-plus/icons-vue'
import LayoutNav from '../Layout/components/LayoutNav.vue';
import LayoutFooter from '../Layout/components/LayoutFooter.vue';
import { getGoodsListAPI } from '@/api/store'
import { getWholesalerInfoAPI } from '@/api/wholesaler'




const route = useRoute()
const router = useRouter()

// 批发商信息
const wholesalerInfo = ref({})
// const wholesalerInfo = {
//     id: 1,
//     avatar: 'https://example.com/wholesaler_avatar.jpg',
//     name: '阳光批发商',
//     address: '北京市朝阳区XX大街XX号',
//     phone: '1234567890',
//     description: '我们是一家专业的批发商，提供各类优质商品，服务至上，欢迎合作！'
// };
// 商品列表相关
const goodsList = ref([])
// const goodsList =  ref([
//     {
//         id: 1001,
//         image: 'https://example.com/goods_image1.jpg',
//         name: '时尚T恤',
//         description: '纯棉材质，舒适透气，时尚印花设计，适合日常穿着。',
//         price: 59.99,
//         minOrder: 5
//     },
//     {
//         id: 1002,
//         image: 'https://example.com/goods_image2.jpg',
//         name: '休闲牛仔裤',
//         description: '经典牛仔款式，修身版型，优质牛仔布料，耐穿又时尚。',
//         price: 99.99,
//         minOrder: 3
//     },
//     {
//         id: 1003,
//         image: 'https://example.com/goods_image3.jpg',
//         name: '简约衬衫',
//         description: '纯色简约设计，面料柔软，适合商务和休闲场合。',
//         price: 79.99,
//         minOrder: 4
//   },
//         {
//         id: 1003,
//         image: 'https://example.com/goods_image3.jpg',
//         name: '简约衬衫',
//         description: '纯色简约设计，面料柔软，适合商务和休闲场合。',
//         price: 79.99,
//         minOrder: 4
//   },
//         {
//         id: 1003,
//         image: 'https://example.com/goods_image3.jpg',
//         name: '简约衬衫',
//         description: '纯色简约设计，面料柔软，适合商务和休闲场合。',
//         price: 79.99,
//         minOrder: 4
//     },
//     // 可以继续添加更多商品数据
// ]);

const pageList = ref([]); // 当前页的数据（用于显示）
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 获取批发商信息
const getWholesalerInfo = async () => {
  const res = await getWholesalerInfoAPI(route.params.userId)
  wholesalerInfo.value = res.data
  console.log('userId:',wholesalerInfo.value.userId);
}

// 获取商品列表
const getGoodsList = async () => {
  const res = await getGoodsListAPI(route.params.userId)
  // console.log(res.data)
  goodsList.value = res.data
  total.value = goodsList.value.length
  updatePaginatedList();   // 更新分页数据
}
getGoodsList()

const searchKeyword = ref('')

// 添加一个计算属性用于过滤商品列表
const filteredGoodsList = computed(() => {
  if (!searchKeyword.value) {
    return goodsList.value
  }
  return goodsList.value.filter(item => 
    item.good_name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 添加搜索处理方法
const handleSearch = () => {
  currentPage.value = 1 // 重置页码到第一页
  updatePaginatedList()
}

// 监听搜索关键词变化
watch(searchKeyword, () => {
  if(searchKeyword.value === '')
  handleSearch()
})


// 联系批发商
const handleContact = () => {
  router.push({
    name: 'customer',
    params: { userId: wholesalerInfo.value.userId }
    // query: {
    //   targetId: wholesalerInfo.value.userId,
    //   targetName: wholesalerInfo.value.name,
    //   targetAvatar: wholesalerInfo.value.avatar
    // }
  })
}

// 跳转到商品详情
const goToGoodsDetail = (id) => {
  const routeData = router.resolve({
    name: 'goodDetail',
    params: { userId: wholesalerInfo.value.userId, goodId: id }
  })
  // 在新窗口打开
  window.open(routeData.href, '_blank')
}

// 分页处理
// 修改更新分页数据的方法，使用过滤后的列表
const updatePaginatedList = () => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  // 使用过滤后的列表
  pageList.value = filteredGoodsList.value.slice(start, end)
  // 更新总数
  total.value = filteredGoodsList.value.length
}

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize; // 更新每页显示的条目数
  updatePaginatedList();  // 更新分页数据
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage; // 更新当前页码
  updatePaginatedList();  // 更新分页数据
};

// 页面加载时获取数据
onMounted(() => {
  getWholesalerInfo()
  getGoodsList()
})
</script>

<style lang="scss" scoped>
.container{
  min-height: 100vh;
  position: relative;
  .pagination{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 20px;
  }
}
.wholesaler-detail {
  padding: 20px;
  
  .info-card {
    margin-bottom: 20px;
    
    .wholesaler-info {
      display: flex;
      gap: 20px;
      
      .right {
        flex: 1;
        
        .name {
          margin: 0 0 15px 0;
          font-size: 24px;
        }
        
        .info-item {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          color: #666;
          
          .el-icon {
            margin-right: 8px;
          }
        }
        
        .actions {
          margin-top: 20px;
        }
      }
    }
  }
  
  .goods-section {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h3 {
        margin: 0;
      }
      
      .filters {
        display: flex;
        gap: 15px;
      }
    }
    
    .goods-card {
      margin-bottom: 20px;
      cursor: pointer;
      
      .goods-image {
        width: 100%;
        height: 200px;
      }
      
      .goods-info {
        padding: 10px;
        
        .goods-name {
          margin: 0 0 8px 0;
          font-size: 16px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .goods-desc {
          color: #666;
          font-size: 14px;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .price {
            color: #ff6b6b;
            font-size: 18px;
            font-weight: bold;
          }
          
          .min-order {
            color: #999;
            font-size: 12px;
          }
        }
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>